package until;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBuntil {

    private static String DRI;
    private static String URL;
    private static String USE;
    private static String PWD;

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConn() {
        Connection conn = null;
        try {
            readCon();
            Class.forName(DRI);
            conn = DriverManager.getConnection(URL, USE, PWD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 读取配置文件
     */
    public static void readCon() throws IOException {
        InputStream in = DBuntil.class.getClassLoader().getResourceAsStream("databases.properties");
        Properties pro = new Properties();
        pro.load(in);
        DRI = pro.getProperty("classdriver");
        URL = pro.getProperty("url");
        USE = pro.getProperty("user");
        PWD = pro.getProperty("password");
    }

    /**
     * 关闭数据库
     * @param con
     * @param st
     * @param rs
     */
    public static void cloAll(Connection con, Statement st, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
